<template>
    <div class="ordering">
        <!-- 头部 -->
        <div class="heading">购物车</div>
        <!-- 内容区域 -->
        <div class="content-view">
            <el-table ref="table" :data="cartItems" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"/>
                <el-table-column align="center" hidden="hidden" label="序列" type="index" width="80px"/>
                <el-table-column label="商品图片" prop="dishImage">
                    <template slot-scope="scope">
                        <img :src="'http://localhost:8501' + scope.row.dishImage" alt=""
                             style="width: 100px; height: 80px;">
                    </template>
                </el-table-column>
                <el-table-column label="商品名称" prop="dishName"/>
                <el-table-column label="单价" prop="dishPrice" width="100px"/>
                <el-table-column label="数量" min-width="150px" prop="dishNum">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.dishNum" :min="1" size="small"
                                         @change="updateQuantity(scope.row)"/>
                    </template>
                </el-table-column>
                <el-table-column label="总价" prop="dishTotalPrice" width="100px"/>
                <el-table-column label="操作" width="100px">
                    <template slot-scope="scope">
                        <el-button type="danger" @click="removeItem(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="cart-actions">
                <div class="action-buttons">
                    <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
                    <el-button type="danger" @click="removeSelectedItems">删除选中商品</el-button>
                    <el-button type="primary" @click="handlePay">结算</el-button>
                </div>
                <div class="pagination">
                    <el-pagination
                            :current-page="pageable.pageNum"
                            :page-size="pageable.pageSize"
                            :total="pageable.total"
                            layout="total, prev, pager, next"
                            @current-change="handlePageChange"
                    >
                    </el-pagination>
                </div>
                <div class="total-price">
                    总价: ¥{{ totalPrice.toFixed(2) }}
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import {deleteShopCarApi, deleteShopCarBatchApi, getShopCarApi, payApi, updateShopCarApi} from "@/api/dish";
import {getUserInfo} from "@/utils/auth";

export default {
    name: 'Cart',
    data() {
        return {
            cartItems: [],
            selectedItems: [],
            pageable: {pageNum: 1, pageSize: 5, total: 0},
            selectAll: false,
            uid: JSON.parse(getUserInfo()).id
        };
    },
    computed: {
        totalPrice() {
            return this.selectedItems.reduce((total, item) => total + item.dishPrice * item.dishNum, 0);
        }
    },
    watch: {
        selectAll(val) {
            this.handleSelectAll(val);
        }
    },
    mounted() {
        this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
    },
    methods: {
        async getShopCar(pageNum, pageSize, id) {
            try {
                const response = await getShopCarApi({pageNum, pageSize, id});
                const data = response.data;
                this.cartItems = data.list;
                this.pageable.pageNum = data.pageNum;
                this.pageable.pageSize = data.pageSize;
                this.pageable.total = data.total;
                this.selectedItems = this.cartItems.filter(item => item.selected);
            } catch (error) {
                console.error('Failed to fetch shopping cart:', error);
            }
        },
        updateQuantity(item) {
            console.log(item)
            item.dishTotalPrice = item.dishPrice * item.dishNum;
            updateShopCarApi(item).then(() => {
                this.$message.success('操作成功');
                this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
            }).catch((error) => {
                console.error('Failed to update quantity:', error);
            });
        },
        removeItem(item) {
            this.$confirm('是否确认删除该商品？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteShopCarApi(item.id).then(() => {
                    this.$message.success('操作成功');
                    this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
                }).catch((error) => {
                    console.error('Failed to update quantity:', error);
                });
            }).catch(() => {
                // 处理取消的情况
                this.$message.info('取消删除');
            });
        },
        handleSelectionChange(val) {
            this.selectedItems = val;
            this.selectAll = this.selectedItems.length === this.cartItems.length;
        },
        handleSelectAll(val) {
            if (val) {
                this.$refs.table.clearSelection();
                this.cartItems.forEach(item => {
                    this.$refs.table.toggleRowSelection(item, true);
                });
            } else {
                this.$refs.table.clearSelection();
            }
        },
        removeSelectedItems() {
            if (this.cartItems.length === 0 || this.selectedItems.every(item => item.count === 0)) {
                this.$message.warning('所选项为空！');
                return;
            }
            this.$confirm('是否确认删除该商品？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const ids = this.selectedItems.map(item => item.id).join(',');
                deleteShopCarBatchApi({ids}).then(() => {
                    this.$message.success('操作成功');
                    this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
                }).catch((error) => {
                    console.error('Failed to delete item:', error);
                });
            });
        },
        handlePageChange(page) {
            this.pageable.pageNum = page;
            this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
        },
        handlePay() {
            if (this.cartItems.length === 0 || this.selectedItems.every(item => item.count === 0)) {
                this.$message.warning('购物车为空，无法结算！');
                return;
            }
            // 调用结算接口
            payApi({
                userId: this.uid,
                ids: this.selectedItems.map(item => item.id).join(',')
            }).then(() => {
                this.$message.success('创建订单成功！');
                this.getShopCar(this.pageable.pageNum, this.pageable.pageSize, this.uid);
            }).catch(error => {
                console.error('结算失败：', error);
                this.$message.error('结算过程中发生错误，请稍后再试！');
            });
        }
    }
}
</script>

<style scoped>
.cart-page {
    padding: 20px;
}

.heading {
    font-size: 2em;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: center;
}

.content-view {
    margin-top: 20px;
}

.cart-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.action-buttons {
    display: flex;
    align-items: center;
}

.action-buttons .el-checkbox {
    margin-right: 10px;
}

.pagination {
    flex-grow: 1;
    display: flex;
    justify-content: center;
}

.total-price {
    font-size: 1.5em;
    font-weight: bold;
}
</style>
